//
//  OonlineCell.m
//  Molian
//
//  Created by 胡津 on 30/6/15.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

#import "OonlineCell.h"
#import "MLTabBar.h"
#import "MLHomeViewController.h"
#import "LoginViewController.h"

@implementation OonlineCell

- (void)awakeFromNib {
    // Initialization code
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.is = NO;
        CGFloat CellHeight = 84;
        CGFloat Cellwidth = DeviceWidth;
        
        //用户头像
        self.userAvatarImg = [[UIImageView alloc]init];
        self.userAvatarImg.frame = CGRectMake(8, (CellHeight-65)/2, 65, 65);
        self.userAvatarImg.layer.masksToBounds = YES;//开启圆角
        [self.userAvatarImg.layer setCornerRadius:4];
        [self.userAvatarImg setContentMode:UIViewContentModeScaleAspectFill];
        [self.topContentView addSubview:self.userAvatarImg];
        
        
        //用户名字
        self.userNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(78, 12, DeviceWidth-134, 24)];
        [self labelStyle:self.userNameLabel];
        self.userNameLabel.textColor = RGBA(51, 51, 51, 1);
        self.userNameLabel.font = [UIFont fontWithName:FontName size:16];
        [self.topContentView addSubview:self.userNameLabel];
        
        
                self.userSeriesLabel.backgroundColor = [UIColor colorWithRed:arc4random_uniform(255) / 255.0f
                                                                       green:arc4random_uniform(255) / 255.0f
                                                                        blue:arc4random_uniform(255) / 255.0f alpha:1];
        
        //喜欢按钮
        self.userLikeBtn = [[LikeButton alloc]initWithFrame:CGRectMake(Cellwidth-108, 12, 100, 25)];
        [self.userLikeBtn addTarget:self action:@selector(likeUser) forControlEvents:UIControlEventTouchUpInside];
        [self.topContentView addSubview:self.userLikeBtn];
        
        
        //用户年龄
        self.userAgeLabel = [[UIButton alloc]init];
        self.userAgeLabel.frame = CGRectMake(78, 38, 22, 12);
        [self labelStyle:self.userAgeLabel.titleLabel];
        [self.userAgeLabel.layer setCornerRadius:6];
        self.userAgeLabel.clipsToBounds = YES;
        self.userAgeLabel.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        self.userAgeLabel.contentEdgeInsets = UIEdgeInsetsMake(1, 0, 0, 0);
        [self.userAgeLabel setBackgroundImage:[UIImage imageNamed:@"boy_age"] forState:UIControlStateNormal];
        [self.topContentView addSubview:self.userAgeLabel];
        self.userAgeLabel.userInteractionEnabled = NO;
        
        
//        //钱
//        self.RECOMMENDED = [[UIButton alloc] init];
//        [self.RECOMMENDED setImage:[UIImage imageNamed:@"icon_excellent_lover"] forState:UIControlStateNormal];
//        [self.topContentView addSubview:self.RECOMMENDED];
//        self.RECOMMENDED.userInteractionEnabled = NO;
        
        
        //用户系列
        self.userSeriesLabel = [[UIButton alloc]init];
       // [self.userSeriesLabel setBackgroundImage:[UIImage imageNamed:@"知性暖男系"] forState:UIControlStateNormal];
        [self.userSeriesLabel setTitleColor:RGBA(122, 122, 122, 1) forState:UIControlStateNormal];
        self.userSeriesLabel.titleLabel.font = kFont(10);
        
        
        [self.topContentView addSubview:self.userSeriesLabel];
        self.userSeriesLabel.userInteractionEnabled = NO;
        
        
        //用户地址+星座
        self.userInfo = [[UILabel alloc]init];
        [self labelStyle:self.userInfo];
        self.userInfo.textColor = [UIColor grayColor];
        [self.topContentView addSubview:self.userInfo];
        
        //用户签名
        self.userSignatureLabel = [[UILabel alloc]init];
        self.userSignatureLabel.frame = CGRectMake(78, 52, Cellwidth-86, 20);
        [self labelStyle:self.userSignatureLabel];
        self.userSignatureLabel.font = [UIFont fontWithName:FontName size:11];
        self.userSignatureLabel.textColor = RGBA(102, 102, 102, 1);
        [self.topContentView addSubview:self.userSignatureLabel];
        
        
        CATransition *trans=[[CATransition alloc]init];
        [trans setType:kCATransitionReveal];
        [trans setSubtype:kCATransitionFromLeft];
        [trans setDuration:0.5];
        [self.layer addAnimation:trans forKey:nil];
        
    }
    return self;
    
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
    NSDictionary * dic = [[NSDictionary alloc]initWithObjectsAndKeys:self.userLikeBtn.Title.font,NSFontAttributeName,nil];
    CGSize size = [self.userLikeBtn.Title.text sizeWithAttributes:dic];
    self.userLikeBtn.frame = CGRectMake(DeviceWidth - size.width - 40, 12, size.width + 30, 25);
    
    self.userNameLabel.frame = CGRectMake(78, 12, DeviceWidth- (size.width + 124), 24);
    
    
    CGFloat interval = 0;
    
    
    if (self.userSeriesLabel.selected == YES) {
        self.userSeriesLabel.hidden = NO;
        self.userSeriesLabel.frame = CGRectMake(102+interval, 39, 64, 12);
        interval += 64;
    }else{
        self.userSeriesLabel.hidden = YES;
        interval += 0;
    }
    
//    if (self.RECOMMENDED.selected == YES) {
//        self.RECOMMENDED.hidden = NO;
//        self.RECOMMENDED.frame = CGRectMake(102+interval, 38, 18, 12);
//        interval += 18;
//    }else{
//        self.RECOMMENDED.hidden = YES;
//        interval += 0;
//    }
    self.userInfo.frame = CGRectMake(104+interval, 39, 90, 12);
}

// 喜欢用户
- (void)likeUser {
    
    if (![Utils userinit:self.tabbar]) {
        return;
    }
    [ShareData shareData].isLike = YES;
    if (_userLikeData.type == 0) {
        [AVAnalytics event:@"喜欢实习恋人"]; // 通知服务器一个点击事件。
    }else{
        [AVAnalytics event:@"喜欢无独团"]; // 通知服务器一个点击事件。
    }
    
    //防止多次点击
    if (self.is) {
        //正在请求数据,不执行
    }else{
        self.is = YES;//开始请求数据
        // MLTabBar *tabBar = (MLTabBar *)self.tabbar;
        // MLHomeViewController *homeView = (MLHomeViewController *)tabBar.homeNavigation.topViewController;
        
        ShareData *shareData = [ShareData shareData];
        if (!self.userLikeBtn.status) {
            
            BOOL isLike = NO;//是否在喜欢的列表
            if ([Utils isLoveUserObjectId:self.userLikeData.objectId]) {
                isLike = YES;
            }
            if (isLike) {
                //已存在
                self.is = NO;//请求数据成功
                NSInteger likecount = [self.userLikeBtn.Title.text integerValue];
                if(likecount<0){
                    likecount = 0;
                }
                likecount ++;
                self.userLikeBtn.Title.text = [NSString stringWithFormat:@"%ld",(long)likecount];
                [[ShareData shareData].likeUserDic setObject:[NSString stringWithFormat:@"%ld",(long)likecount] forKey:self.userLikeData.objectId];
                [Utils savePassLoveUserObjectID:self.userLikeData.objectId];
                self.userLikeBtn.status = YES;
                [self.userLikeBtn Like:YES Alpha:0.4];
                
            }else{
                
                MLUserLike *userLike = [MLUserLike object];
                userLike.user = [MLUser currentUser];
                userLike.likeUser = self.userLikeData;
                [userLike saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                    self.is = NO;//请求数据成功
                    if (!error) {
                        NSLog(@"成功");
                    }else{
                        NSLog(@"%@",error);
                    }
                    // 添加到喜欢的列表中, 修改喜欢的状态
                    if (succeeded) {
                        self.userLikeBtn.status = YES;
                        NSInteger likecount = [self.userLikeBtn.Title.text integerValue];
                        if(likecount<0){
                            likecount = 0;
                        }
                        likecount ++;
                        self.userLikeBtn.Title.text = [NSString stringWithFormat:@"%ld",(long)likecount];
                        [[ShareData shareData].likeUserDic setObject:[NSString stringWithFormat:@"%ld",(long)likecount] forKey:self.userLikeData.objectId];
                        [self.userLikeBtn Like:YES Alpha:0.4];
                        [Utils savePassLoveUserObjectID:self.userLikeData.objectId];
                        // 标记已喜欢的状态
                        NSDictionary *params = @{@"userId": self.userLikeData.objectId};
                        [AVCloud callFunctionInBackground:@"likeUser" withParameters:params block:^(id object, NSError *error) {
                            
                            if (error) {
                                //   [HUD Prompt:@"网络错误,请重试"];
                            }else{
                                
                                NSString *str = [NSString stringWithFormat:@"%@喜欢了你，快去翻翻看",[MLUser currentUser].nickname];
                                NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:
                                                      str, @"alert",
                                                      @"default", @"sound",NOTIFICATION_TYPE_NEW_LIKE_PUSH,@"action",
                                                      nil];
                                // NSDictionary *data = @{@"aps":@{@"alert":str,@"badge":@"Increment",@"sound":@"default"}};
                                AVPush *push = [[AVPush alloc] init];
                                //正式需要注销下面代码
                                //  [AVPush setProductionMode:NO];
                                [push setChannels:[NSArray arrayWithObjects:self.userLikeData.objectId, nil]];
                                [push setData:data];
                                [push sendPushInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                                    NSLog(@"error%@",error);
                                }];
                                
                                NSDictionary *params = @{@"touserId": self.userLikeData.objectId, @"fromuserId": [MLUser currentUser].objectId,@"nick":[MLUser currentUser].nickname,@"msg":@"给你点赞了哦"};
                                [AVCloud callFunctionInBackground:@"sendNewLikerMsg" withParameters:params block:^(id object, NSError *error) {
                                    if (error) {
                                        [HUD Prompt:@"网络错误,请重试"];
                                    }else{
                                        
                                    }
                                }];
                            }
                        }];
                    }
                    
                }];
            }
        }else{
            
            AVQuery *q = [MLUserLike query];
            [q whereKey:@"user" equalTo:[MLUser currentUser]];
            [q whereKey:@"likeUser" equalTo:self.userLikeData];
            [q deleteAllInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                self.is = NO;
                if(!error){
                    NSInteger likecount = [self.userLikeBtn.Title.text integerValue];
                    likecount --;
                    NSLog(@"%ld",(long)likecount);
                    if(likecount<0){
                        likecount = 0;
                    }
                    //请求数据成功
                    NSLog(@"%ld",(long)likecount);
                    self.userLikeBtn.status = NO;
                    self.userLikeBtn.Title.text = [NSString stringWithFormat:@"%ld",(long)likecount];
                    [[ShareData shareData].likeUserDic setObject:[NSString stringWithFormat:@"%ld",(long)likecount] forKey:self.userLikeData.objectId];
                    [self.userLikeBtn Like:NO Alpha:0.4];
                    [Utils removeObjectForLoveUserObjectID:self.userLikeData.objectId];
                    NSDictionary *params = @{@"userId": self.userLikeData.objectId};
                    [AVCloud callFunctionInBackground:@"disLikeUser" withParameters:params block:^(id object, NSError *error) {
                        if (error) {
                            //[HUD Prompt:@"网络错误,请重试"];
                        }else{
                            
                        }
                    }];
                }else{
                    self.is = NO;//请求数据成功
                    [HUD Prompt:@"网络错误,请重试"];
                }
            }];
        }
    }
}

-(UILabel *)labelStyle:(UILabel *)label//统一风格
{
    label.textColor = [UIColor blackColor];
    label.textAlignment = NSTextAlignmentLeft;
    label.font = [UIFont fontWithName:FontName size:10];
    return label;
}



- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}

@end
